<?php
namespace StarCloud\Models;

use Hashids\Hashids;
use Phalcon\Validation;
use Phalcon\Validation\Validator\StringLength;

trait InviteCode
{
    public function validation()
    {
        $validator = new Validation();

        $validator->add('code', new StringLength(['max' => 10]));

        return $this->validate($validator);
    }

    public static function getInviteCode($uid)
    {
        if (false == ($newCode = self::findFirstByUid($uid))) {
            $newCode = new self();
            $newCode->uid = $uid;
            $newCode->code = self::generateUniqCode($uid);
            $newCode->save();
        }

        return $newCode->getCode();
    }

    public static function generateUniqCode($uniqNumber)
    {
        $salt = 'p4f28Gc6R57nk5';
        $minLength = 6;
        $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';

        $hashids = new Hashids($salt, $minLength, $alphabet);

        return $hashids->encode($uniqNumber);
    }

    // invite_codes表字段
    protected $id;
    protected $uid;
    protected $code;
    protected $created_at;
}
